package com.CloudTasks2;

import com.CloudTasks2.EMF;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiFrontendLimits;

import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Query;

@Api(frontendLimits
    = @ApiFrontendLimits
      (unregisteredQps=-1, unregisteredUserQps=-1, unregisteredDaily=-1))
public class TaskService {

  /**
   * This method lists all the java bean objects inserted in datastore.
   * It uses HTTP GET method.
   *
   * @return List of all java bean objects persisted.
   */
  public List<Task> listTask() {
    EntityManager mgr = null;
    List<Task> execute = null;
    try{
      mgr = getEntityManager();
      Query query = mgr.createQuery("select from Task");
      execute = (List<Task>) query.getResultList();
      // Tight loop for fetching all entities from datastore and accomodate
      // for lazy fetch.
      for (Task e:execute);
    } finally {
      mgr.close();
    }
    return execute;
  }

  /**
   * This method gets the entity having primary key id. It uses HTTP GET method.
   *
   * @param id the primary key of the java bean.
   * @return The java bean object with primary key id.
   */
  public Task getTask(@Named("id") Long id) {
    EntityManager mgr = null;
    Task e  = null;
    try {
      mgr = getEntityManager();
      e = mgr.find(Task.class, id);
    } finally {
      mgr.close();
    }
    return e;
  }

  /**
   * This inserts the java bean object e into App Engine datastore.
   * It uses HTTP POST method.
   *
   * @param e the java bean object to be inserted.
   * @return The inserted java bean object.
   */
  public Task insertTask(Task e) {
    EntityManager mgr = null;
    try {
      mgr = getEntityManager();
      mgr.persist(e);
    } finally {
      mgr.close();
    }
    return e;
  }

  /**
   * This method is used for updating a java bean object e.
   * It uses HTTP PUT method.
   *
   * @param e the java bean object to be updated.
   * @return The updated java bean object.
   */
  public Task updateTask(Task e) {
    EntityManager mgr = null;
    try {
      mgr = getEntityManager();
      mgr.persist(e);
    } finally {
      mgr.close();
    }
    return e;
  }

  /**
   * This method removes the entity with primary key id.
   * It uses HTTP DELETE method.
   *
   * @param id the primary key of the java bean object to be deleted.
   * @return The deleted java bean object.
   */
  public Task removeTask(@Named("id") Long id) {
    EntityManager mgr = null;
     Task e  = null;
    try {
      mgr = getEntityManager();
      e = mgr.find(Task.class, id);
      mgr.remove(e);
    } finally {
      mgr.close();
    }
    return e;
  }

  private static EntityManager getEntityManager() {
    return EMF.get().createEntityManager();
  }

}
